<?php

namespace MoChat\App\Sales\Action\Task;

use MoChat\App\Sales\Contract\SalesTaskContract;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 创建销售任务
 * @Controller
 */
class Create extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var SalesTaskContract
     */
    protected $salesTaskService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/salesTask/create", methods="POST")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $this->salesTaskService->createSalesTask([
            'name'=>$data['name'],
            'corp_id' => reset($user['corpIds']),
            'work_department_id' => $data['work_department_id'],
            'start_time' => $data['start_time'],
            'end_time' => $data['end_time'],
            'sales_task' => $data['sales_task'],
            'remark' => $data['remark'] ?? '',
            'created_at' => date('Y-m-d H:i:s')
        ]);
        return [];
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'name'=>'required|max:30',
            'work_department_id' => 'required|integer',
            'start_time' => 'required',
            'end_time' => 'required',
            'sales_task' => 'required|numeric',
            'remark' => 'max:100'
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'name.required'=>'任务名称未填写',
            'name.max'=>'任务名称不能超过30个字符串',
            'work_department_id.required' => '部门未选择',
            'work_department_id.integer' => '部门参数错误',
            'start_time.required' => '任务开始时间不能为空',
            'end_time.required' => '任务结束时间不能为空',
            'sales_task.required' => '销量指标不能为空',
            'sales_task.numeric' => '销量指标参数错误',
            'remark.max' => '备注参数长度不能超过100个字符'
        ];
    }
}